import {
  getStorage,
  setStorage,
  formatDate,
  setBarText,
} from "./common.js";
import {
  getDueTasks,
} from "./dates.js";

/**
 * @description 检查今天是否有事件到期
 * @author start2004
 * @since 2025-09-15
 */
async function isToday(){
  /**
   * @since 2025-09-15 检查任务今天是否执行过
   */
  let executed = await hasTaskBeenExecutedToday();
  if(executed){
    setBarText("");
    return;
  } else {}

  /**
   * @since 2025-09-25 获取到期任务
   */
  let dueTasks = await getDueTasks();
  // console.log(dueTasks);

  /**
   * @since 2025-09-15 通知到期的任务，设置图标上数字
   */
  await notifyDueTasks(dueTasks);
}

/**
 * 检查任务今天是否执行过
 * @author start2004
 * @since 2025-09-15
 *
 * @return boolean 执行标志
 */
async function hasTaskBeenExecutedToday(){
  const today = formatDate(new Date(), "zh_CN");

  /**
   * @since 2025-09-15 获取上次执行的日期
   */
  const executeDayKey = "dc-execute-day";
  let executeDayVal = await getStorage(executeDayKey);
  if(executeDayVal === today) return true;

  /**
   * @since 2025-09-15 未执行，更新
   */
  await setStorage(executeDayKey, today);
  return false;
}



/**
 * @description 通知到期的任务
 * @author start2004
 * @since 2025-09-15
 *
 * @param dueTasks {array} - 过期任务
 */
async function notifyDueTasks(dueTasks){
  /**
   * @since 2025-09-26 到期任务的数量
   */
  let cnt = dueTasks.length;
  if(cnt == 0) return;
  let text = cnt.toString();
  if(cnt > 9) text = "9+";

  /**
   * @since 2025-09-26 图标上显示到期任务的数量
   */
  setBarText(text);

  /**
   * @since 2025-09-26 弹窗提示
   */
  const w = 400, h = 400;
  const win = await chrome.windows.getCurrent();
  const left = win.left + Math.round((win.width - w) / 2);
  const top = win.top + Math.round((win.height - h) / 2);
  const p = {
    width: w,
    height: h,
    type: 'popup',
    left: left,
    top: top,
    url: chrome.runtime.getURL("../../pages/today.html")
  };
  chrome.windows.create(p);
}

/**
 * @description 浏览器启动时触发
 * @author start2004
 * @since 2025-09-15
 */
chrome.runtime.onStartup.addListener(async() => {
  setTimeout(function (){
    isToday();
  }, 3000);
});

/**
 * @description 监听popup透传信息
 * @author start2004
 * @since 2025-09-25
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "check-due-tasks") isToday();
});